<?php
/**
 * Joomla! 1.5 component myApi
 *
 * @version $Id: controller.php 2010-05-01 08:43:14 svn $
 * @author Thomas Welton
 * @package Joomla
 * @subpackage myApi
 * @license GNU/GPL
 *
 * myApi - Combining the power of the Facebook platform with the ease and simplicity of Joomla.
 *
 * This component file was created using the Joomla Component Creator by Not Web Design
 * http://www.notwebdesign.com/joomla_component_creator/
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

/**
 * myApi Component Controller
 */
class MyapiController extends JController {
	function display() {
        // Make sure we have a default view
        if( !JRequest::getVar( 'view' )) {
		    JRequest::setVar('view', 'myapi' );
        }
		parent::display();
	}
	
	function syncPhoto($id,$uid){
		if(JRequest::getVar('pic','') != ''){
			$dest = JPATH_SITE.DS.'images'.DS.'comprofiler'.DS.'gallery'.DS.'facebookUID'.$uid.'.jpg';
			$avatar = 'gallery'.DS.'facebookUID'.$uid.'.jpg';
			
			copy(JRequest::getVar('pic',''),$dest);
			$db =& JFactory::getDBO();
			$query = "UPDATE #__comprofiler SET avatar ='".$avatar."' WHERE user_id ='".$id."'";
			$db->setQuery($query);
			$db->Query();
		}
		
		
		return;
		// end new code
	
	}
	function updateComments(){
		$uid = JRequest::getVar('uid','','get');
		$xid = JRequest::getVar('xid','','get');
		$pic = JRequest::getVar('pic','','get');
		$url = base64_decode(JRequest::getVar('url','','get'));
		echo $url;
		global $facebook;
		
		
		$query = "SELECT text FROM comment WHERE xid='".$xid."' AND fromid='".$uid."' ORDER BY time DESC LIMIT 1";
		try{
		$array =  $facebook->api(array('method' => 'fql_query','query'=>$query));
		}catch(Exception $e) { echo $e; }
		
		$config =& JFactory::getConfig();
		$sitename = $config->getValue( 'config.sitename' );
				
		$message = $array[0]['text'];
		$attachment = array(
			'name' => 'Comments from '.$sitename,
			'href' => $url,
			'caption' => '{*actor*} posted a comment about on the article  "'.$title.'" from '.$sitename
	  );
		$action_links = array('text' => 'See the full article',
			'href' => $url);
			
			
		
		$com_params = &JComponentHelper::getParams( 'com_myapi' );
		$target_id = $com_params->get('appId');
		echo $target_id;
	
		   try {
                $statusUpdate = $facebook->api('/'.$target_id.'/feed', 'post', array(
               'message'=>$message, 
			   'link'=>$url,
			   'name'=>'Read the article this comment was made on',
			   'description'=>'This comment was automatically imported using myApi'
                ));
            } catch (FacebookApiException $e) {
                echo $e;
            }
		  
	  
	  global $mainframe;
	  $mainframe->close();
					
				
			
	
		
	}
	
	//This task logs in a user
	function facebookLogin() {
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		
		require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_myapi'.DS.'models'.DS.'facebook.php';
		$facebookmodel = new myapiModelfacebook;  //Bring the myAPI facebook model
		$fbUser = $facebookmodel->getLoggedInUser();
		$uid = $fbUser['id'];
		$return = JRequest::getVar('return','','post');
		$user = JFactory::getUser();
		if($uid):
			global $mainframe;
			$db =& JFactory::getDBO();
			$query = "SELECT userId FROM ".$db->nameQuote('#__myapi_users')." WHERE ".$db->nameQuote('uid')." = ".$db->quote($uid);
			$db->setQuery( $query );
			$db->query();
			$num_rows = $db->getNumRows();
			$query_id = $db->loadResult();
			if($num_rows!=0)
			{
				if($user->guest){
					$options['fake_array'] = "This mainframe->login needs and array passed to it";
					$error = $mainframe->login($uid,$options);
					if($error->level != '2')
					{
						$this->syncPhoto($query_id,$uid);
						if($return == '') { $this->setRedirect(JURI::base(),JText::_( 'LOGGED_IN_FACEBOOK' )); }
						else { $this->setRedirect($return,JText::_( 'LOGGED_IN_FACEBOOK' )); }
					}
					else{ $this->setRedirect(JURI::base(),JText::_( 'LOGIN_ERROR' )." - ".$uid); }
				}elseif($query_id != $user->id){
					//If the user is logged then the facebook link must be for another joomla account
					$this->setRedirect(JURI::base(),JText::_('DOUBLE_LINK'));
				}
				else{
					$this->syncPhoto($query_id,$uid);
					 if(JRequest::getVar('return','') == '') { $this->setRedirect(JURI::base(),JText::_( 'LOGGED_IN_FACEBOOK' )); }
					 else { $this->setRedirect($return,JText::_( 'LOGGED_IN_FACEBOOK' )); }
				}
				
			}
			else
			{
				return false; //No link found
				
					
			}
		else:
			$this->setRedirect($return,JText::_('NO_SESSION'));
		endif;
	}
	
	
	function logout(){
	
		global $mainframe;
		$mainframe->logout();
		global $facebook;
		$facebook->setSession(null);
		
		if(JRequest::getVar('auto','0','get') == '0'){
			$this->setRedirect(JURI::base(),JText::_('FACEBOOK_LOGOUT'));
		}else{
			$this->setRedirect(JURI::base(),JText::_('FACEBOOK_EXPIRED'));
		}
	
	}
	//Joomla user login task
	function login()
	{
		// Check for request forgeries
		JRequest::checkToken('request') or jexit( 'Invalid Token' );

		global $mainframe;

		$return = JRequest::getVar('return', '', 'method', 'base64');
			

		$options = array();
		$options['remember'] = JRequest::getBool('remember', false);
		$options['return'] = $return;

		$credentials = array();
		$credentials['username'] = JRequest::getVar('username', '', 'method', 'username');
		$credentials['password'] = JRequest::getString('passwd', '', 'post', JREQUEST_ALLOWRAW);

		//preform the login action
		$error = $mainframe->login($credentials, $options);
		$message = JText::_( 'LOGGED_IN_FACEBOOK' );
		if(JError::isError($error))
		{
			$message = $error->message;
		}
		
		
		$this->setRedirect($return,$message);
	}
	
	//A function called via ajax to see is a Facebook user is linked to a Joomla user, returns true or false
	function isLinked(){
		JRequest::checkToken( 'get' ) or die( 'Invalid Token' );
		$db = JFactory::getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__myapi_users')." WHERE uid =".$db->quote(JRequest::getVar('fbId','','get'));
		$db->setQuery($query);
		$db->query();
		$num_rows = $db->getNumRows();
		if($num_rows == 0){ echo 0; }
			else { echo 1; }
		global $mainframe;
		$mainframe->close();
	}

	function newLink(){
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		if($fbUser['id'] != ''){
			$user = JFactory::getUser();
			$db = JFactory::getDBO();
			require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_myapi'.DS.'models'.DS.'facebook.php';
			$facebookmodel = new myapiModelfacebook;  //Bring the myAPI facebook model
			$fbUser = $facebookmodel->getLoggedInUser();
			$query = "INSERT INTO ".$db->nameQuote('#__myapi_users')." (userId,uid) VALUES(".$db->quote($user->id).",".$db->quote($fbUser['id']).")";
			$db->setQuery($query);
			$db->query();
			$this->syncPhoto($user->id,$fbUser['id']);
			
			$this->setRedirect('index.php',JText::_('LINK_COMPLETE'));
		}
		$this->setRedirect('index.php',JText::_('No Facebook User ID found'));
	}
	
	//New user
	function newUser()
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );
		$return = JRequest::getVar('return','','post');
		// Get required system objects
		$user 		= clone(JFactory::getUser());
		$pathway 	=& $mainframe->getPathway();
		$config		=& JFactory::getConfig();
		$authorize	=& JFactory::getACL();
		$document   =& JFactory::getDocument();

		$usersConfig = &JComponentHelper::getParams( 'com_users' );
		// Initialize new usertype setting
		$newUsertype = $usersConfig->get( 'new_usertype' );
		if (!$newUsertype) {
			$newUsertype = 'Registered';
		}

		// Bind the post array to the user object
		if (!$user->bind( JRequest::get('post'), 'usertype' )) {
			$message = $user->getError();
			$this->setRedirect($return,$message);
		}

		// Set some initial user values
		$user->set('id', 0);
		$user->set('usertype', $newUsertype);
		$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));

		$date =& JFactory::getDate();
		$user->set('registerDate', $date->toMySQL());

		// If user activation is turned on, we need to set the activation information
		$useractivation = $usersConfig->get( 'useractivation' );
		

		// If there was an error with registration, set the message and display form
		if ( !$user->save() )
		{
			$message = $user->getError();
			$this->setRedirect($return,$message);
		}elseif(JRequest::getVar('uid','','post') != ''){
			$db = JFactory::getDBO();
			$query = "INSERT INTO ".$db->nameQuote('#__myapi_users')." (userId,uid) VALUES(".$db->quote($user->id).",".$db->quote(JRequest::getVar('uid','','post')).")";
			$db->setQuery($query);
			$db->query();
			
			//Sync Community Builder
			$sql_sync = "INSERT IGNORE INTO #__comprofiler(id,user_id) SELECT id,id FROM #__users WHERE #__users.id =".$db->Quote($user->id);
			$db->setQuery($sql_sync);
			$db->query();
			$this->syncPhoto($user->id,JRequest::getVar('uid','','post'));
		
	
			// Send registration confirmation mail
			$password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
			$password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email
			myapiController::_sendMail($user, $password);
	
			$message = JText::_( 'LOGGED_IN_FACEBOOK' );
			
			$options['fake_array'] = "This mainframe->login needs and array passed to it";
			$error = $mainframe->login(JRequest::getVar('uid','','post'),$options);
			$this->setRedirect($return,$message);
		}else{
			
			$this->setRedirect($return,'No Facebook User ID found');
			
		}
	}
	
	
	
	function _sendMail(&$user, $password)
	{
		global $mainframe;

		$db		=& JFactory::getDBO();

		$name 		= $user->get('name');
		$email 		= $user->get('email');
		$username 	= $user->get('username');

		$usersConfig 	= &JComponentHelper::getParams( 'com_users' );
		$sitename 		= $mainframe->getCfg( 'sitename' );
		$useractivation = $usersConfig->get( 'useractivation' );
		$mailfrom 		= $mainframe->getCfg( 'mailfrom' );
		$fromname 		= $mainframe->getCfg( 'fromname' );
		$siteURL		= JURI::base();

		$subject 	= sprintf ( JText::_( 'Account details for' ), $name, $sitename);
		$subject 	= html_entity_decode($subject, ENT_QUOTES);

		$message = sprintf ( JText::_( 'SEND_MSG' ), $name, $sitename, $siteURL);
		

		$message = html_entity_decode($message, ENT_QUOTES);

		//get all super administrator
		$query = 'SELECT name, email, sendEmail' .
				' FROM #__users' .
				' WHERE LOWER( usertype ) = "super administrator"';
		$db->setQuery( $query );
		$rows = $db->loadObjectList();

		// Send email to user
		if ( ! $mailfrom  || ! $fromname ) {
			$fromname = $rows[0]->name;
			$mailfrom = $rows[0]->email;
		}

		JUtility::sendMail($mailfrom, $fromname, $email, $subject, $message);

		// Send notification to all administrators
		$subject2 = sprintf ( JText::_( 'Account details for' ), $name, $sitename);
		$subject2 = html_entity_decode($subject2, ENT_QUOTES);

		// get superadministrators id
		foreach ( $rows as $row )
		{
			if ($row->sendEmail)
			{
				$message2 = sprintf ( JText::_( 'SEND_MSG_ADMIN' ), $row->name, $sitename, $name, $email, $username);
				$message2 = html_entity_decode($message2, ENT_QUOTES);
				JUtility::sendMail($mailfrom, $fromname, $row->email, $subject2, $message2);
			}
		}
	}
}
?>